package com.example.webmodule.config.interceptor;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.SocketTimeoutException;

/**
 * @ClassName EY-HttpRetryInterceptor
 * @Description com.example.webmodule.config.interceptor
 * @Author menyj
 * @Date 2025/3/26
 **/
public class HttpRetryInterceptor implements Interceptor {

    private final int maxRetries;

    public HttpRetryInterceptor(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        Response response = null;
        IOException exception = null;

        for (int i = 0; i <= maxRetries; i++) {
            try {
                response = chain.proceed(request);
                if (response.isSuccessful()) {
                    return response;
                }
            } catch (SocketTimeoutException e) {
                exception = e;
                if (i == maxRetries) {
                    break;
                }
                // 等待一段时间后重试
                try {
                    Thread.sleep(1000 * (i + 1));
                }
                catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        throw exception != null ? exception :
                new IOException("Failed after " + maxRetries + " retries");
    }
}
